package com.liber.sun.utils;


import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFileFilter;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


import java.io.*;
import java.net.URL;

import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * Created by sunlingzhi on 2017/10/19.
 */
public class MyFileUtils {

    public static  String getExtension(String fileName)
    {
        if(StringUtils.INDEX_NOT_FOUND==StringUtils.indexOf(fileName,"."))
            return StringUtils.EMPTY;
        String ext=StringUtils.substring(fileName,StringUtils.lastIndexOf(fileName,".")+1);
        return StringUtils.trimToEmpty(ext);
    }

    public static  String getFileNameWithoutExtension(String fileName)
    {
        if(StringUtils.INDEX_NOT_FOUND==StringUtils.indexOf(fileName,"."))
            return StringUtils.EMPTY;
        String fileNameWithoutExtension=StringUtils.substring(fileName,0,StringUtils.lastIndexOf(fileName,"."));
        return StringUtils.trimToEmpty(fileNameWithoutExtension);
    }

    public static boolean writeInputStreamToFile(InputStream inputStream, File f) {
        try {
            FileUtils.copyInputStreamToFile(inputStream,f);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean writeURLToFile(URL url, File f) {
        try {
            FileUtils.copyURLToFile(url,f);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    public static boolean writeStringToFile(String data, File file,String encoding) {
        try {
            FileUtils.writeStringToFile(file,data,encoding);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean AppendStringToFile(String data, File file,String encoding) {
        try {
            FileUtils.writeStringToFile(file,data,encoding,true);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean writeByteArrayToFile( byte[] data,File file) {
        try {
            FileUtils.writeByteArrayToFile(file,data);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public static boolean AppendByteArrayToFile( byte[] data,File file) {
        try {

            FileUtils.writeByteArrayToFile(file,data,true);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }


    public static void mkFolder(String fileName) {
        File f = new File(fileName);
        if (!f.exists()) {
            f.mkdir();
        }
    }

    public static File mkFile(String fileName) {
        File f = new File(fileName);
        try {
            f.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return f;
    }

    public static void deleteFiles(String directoryForDel,boolean keepItself)throws Exception{
        File file=new File(directoryForDel);
        if(keepItself){
            FileUtils.cleanDirectory(file);
        }else{
            FileUtils.deleteDirectory(file);
        }
    }

    public static void deleteFile(File file)throws Exception{
          FileUtils.forceDelete(file);
    }


    public static  void copyFileWithSuffix(File srcDir, File destDir, String suffix){
        IOFileFilter suffixFileFilter = FileFilterUtils.suffixFileFilter(suffix);
        IOFileFilter fileFilter = FileFilterUtils.and(FileFileFilter.FILE, suffixFileFilter);
        try {
            FileUtils.copyDirectory(srcDir,destDir,fileFilter);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public  static  void moveDirectory(File srcDir,File destDir){
        try {
            FileUtils.moveDirectory(srcDir,destDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public  static  void moveFile(File srcFile,File destFile){
        try {
            FileUtils.moveFile(srcFile,destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static String getFileContentByString(File file,String encode){
        try {
            return FileUtils.readFileToString(file,encode);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] getFileContentByByte(File file){
        try {
            return FileUtils.readFileToByteArray(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static  InputStream getFileContentByInputStream(File file){
        try {
            return FileUtils.openInputStream(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static  OutputStream getFileOutputStream(File file,Boolean appendFlag){
        try {
            if(appendFlag==true){
                return FileUtils.openOutputStream(file,true);
            }else{
                return FileUtils.openOutputStream(file);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param directory 遍历的文件夹
     * @param extensions 文件后缀过滤
     * @param recursive   true 为递归，false为非递归
     * @return
     */
    public static Collection<File>  getFileList(File directory,String [] extensions,boolean recursive) {
        return FileUtils.listFiles(directory,extensions,recursive);
    }

    /**
     *
     * @param directory 进行遍历的文件夹
     * @param fileFilter    文件需要满足的过滤器条件后缀
     *                  比如EmptyFileFilter、NameFileFilter、PrefixFileFilter
     *                     并且可以通过FileFilterUtils.and()进行组合
     * @param dirFilter   为空表示不进行递归遍历，DirectoryFileFilter.INSTANCE表示递归遍历文件夹
     * @return   文件
     */
    public static Collection<File>  getFileList( File directory, IOFileFilter fileFilter, IOFileFilter dirFilter) {
        return FileUtils.listFiles(directory,fileFilter, dirFilter);
    }

    public  static  void directoryContains(File directory,File child){
        try {
            FileUtils.directoryContains(directory, child);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static File multipartToFile(MultipartFile multfile) throws IOException {
        File f=new File(System.getProperty("java.io.tmpdir") + System.getProperty("file.separator") +
                multfile.getOriginalFilename());
        MyFileUtils.writeInputStreamToFile(multfile.getInputStream(),f);
        return f;
    }



    public  static String getFileWithSuffixInDirectory(String directoryPath,String suffix){
        File directory = new File(directoryPath);
        Collection<File> fileCollection=getFileList(directory,new String[]{suffix},false);
        if(fileCollection.size()==0){
            return  "no " +suffix +" file";
        }else  if(fileCollection.size()==1){
            Iterator<File> it=fileCollection.iterator();
            File files=it.next();
            return files.getAbsolutePath();
        }else{
            return  "shp文件数目有问题";
        }
    }

    /*
    读取Zip文件中的文件，确定数据的类型
    目前支持tif,shp的判定。
 */
    public static  String getSuffixInZip(String fileName) throws IOException {
        if (MyFileUtils.getExtension(fileName).equals("zip")) {
            File file = new File(fileName);
            ZipFile zf = new ZipFile(file);
            Enumeration items = zf.entries();
            while (items.hasMoreElements()) {
                ZipEntry item = (ZipEntry) items.nextElement();
                String extension = MyFileUtils.getExtension(item.getName());
                if (extension.equals("tif")) {
                    return "tif";
                } else if (extension.equals("shp")) {
                    zf.close();
                    return "shp";
                } else {
                    ;
                }
            }
            zf.close();
            return "UNKNOWN";
        } else {
            return "UNKNOWN";
        }
    }


}
